package top.tungsword.webconsole.config;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
 * @author chenji.yu
 * @date 2020/4/21 18:11
 * @description
 */
@Configuration
public class EhcacheConfig {
    @Value("${spring.cache.ehcache.config}")
    private String ehcacheConfig;

    public static final String LOGIN_CACHE = "loginCache";
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private EhCacheManagerFactoryBean cacheManagerFactoryBean;

    @Bean
    public EhCacheCacheManager cacheManager(){
        EhCacheCacheManager cacheManager = new EhCacheCacheManager();
        cacheManager.setCacheManager(cacheManagerFactoryBean.getObject());
        return cacheManager;
    }

    @Bean
    public EhCacheManagerFactoryBean cacheManagerFactory() throws IOException {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        cacheManagerFactoryBean.setConfigLocation(resourceResolver.getResources(ehcacheConfig)[0]);
        return cacheManagerFactoryBean;
    }

    @Bean
    public Cache loginCache() {
        return cacheManager.getCache(LOGIN_CACHE);
    }

}
